package com.example.administrator.xiaobo.utils;

import android.os.AsyncTask;

import com.example.administrator.xiaobo.bean.VarietyEntrity;
import com.example.administrator.xiaobo.callback.DataCallBackListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kk on 2017/2/8.
 */

public class VarietyTask extends AsyncTask<String, Void, List<VarietyEntrity>> {
    private DataCallBackListener listener;

    public VarietyTask(DataCallBackListener listener) {
        this.listener = listener;
    }

    @Override
    protected List<VarietyEntrity> doInBackground(String... params) {
        String url = params[0];
        String json = MyHttpUtils.getStringFromUrl(url);
        VarietyEntrity varietyEntrity;
        VarietyEntrity.Limage limage;
        VarietyEntrity.Listicon listcon;
        List<VarietyEntrity> datas = new ArrayList<>();
        try {
            if (json != null) {
                JSONObject jsonObject = new JSONObject(json);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsondata = jsonArray.getJSONObject(i);
                    String descrip = jsondata.getString("descrip");
                    String id = jsondata.getString("id");
                    JSONObject limagedata = jsondata.getJSONObject("limage");
                    String level = limagedata.getString("level1");
                    limage = new VarietyEntrity.Limage(level);
                    JSONObject listicondata = jsondata.getJSONObject("listicon");
                    String level2 = listicondata.getString("level1");
                    listcon = new VarietyEntrity.Listicon(level2);
                    String recordparams = jsondata.getString("recordparams");
                    String showtime = jsondata.getString("showtime");
                    String showname = jsondata.getString("showname");
                    String showstatus = jsondata.getString("lstatus");
                    varietyEntrity = new VarietyEntrity(descrip, id, limage, listcon, recordparams,
                            showtime, showname, showstatus);
                    datas.add(varietyEntrity);
                }
                return datas;
            } else {

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<VarietyEntrity> varietyEntrities) {
        super.onPostExecute(varietyEntrities);
        listener.dataCallBackListener(varietyEntrities);
    }
}
